package com.example.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.example.common.util.constant.UserConstants;
import com.example.common.util.core.resultbody.AjaxResult;
import com.example.common.util.utils.StringUtils;
import com.example.model.domain.entity.user.UserInfo;
import com.example.service.util.HttpClientUtils;
import com.example.service.util.service.TokenService;
import com.example.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.service.util.properties.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @Author juzipi
 * @Date 2021/7/19 9:11
 * @Info
 */
@Api(tags = "微信登录")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private TokenService tokenService;



    @ApiOperation("二维码需要的参数")
    @ResponseBody
    @GetMapping("get")
    public AjaxResult getQRContent(){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(UserConstants.APPID, UserPropertiesVariable.appId);
        hashMap.put(UserConstants.SCOPE, UserConstants.SCOPE_VALUE);
        String redirectUri = URLEncoder.encode(UserPropertiesVariable.redirectUrl, StandardCharsets.UTF_8);
        hashMap.put(UserConstants.REDIRECT_URI,redirectUri);
        hashMap.put(UserConstants.STATE,System.currentTimeMillis());
        return AjaxResult.success(hashMap);
    }


    /*
    此处逻辑：前端生成了二维码，用户扫了二维码点击同意后，微信api端会发起一个回调的请求（就是你要访问的路径），
    经过一些逻辑后重定向到了前端的一个路径，那里面的方法就是去登录
    为什么有一个没有用到的参数呢？因为它的接口是需要两个参数的
     */
    @ApiOperation("微信回调方法")
    @GetMapping("callback")
    public String callback(String code,String state){
        //其实就是一个拼接的请求路径， %s 是占位符吧
        String stringBuilder = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(stringBuilder, UserPropertiesVariable.appId, UserPropertiesVariable.appSecret, code);
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String accessToken = jsonObject.getString(UserConstants.ACCESS_TOKEN);
            String openid = jsonObject.getString(UserConstants.OPENID);
            //判断数据库是否存在此用户
            UserInfo userInfo = userInfoService.getUserInfoByOpenId(openid);
            if (StringUtils.isNull(userInfo)){
                //用openid和accessToken请求微信地址，获取扫描人信息
                String baseUserInfo = "https://api.weixin.qq.com/sns/userinfo"+"?access_token=%s"+"&openid=%s";
                String userInfoString = String.format(baseUserInfo, accessToken, openid);
                String resultInfo = HttpClientUtils.get(userInfoString);
                JSONObject parseJson = JSONObject.parseObject(resultInfo);
                String nickname = parseJson.getString(UserConstants.NICKNAME);
                //头像，没设计头像字段
                String avator = parseJson.getString(UserConstants.HEAD_IMG_URL);
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(UserConstants.STATUS_VALUE_NORMAL);
                //新增用户
                userInfoService.insertUserInfo(userInfo);
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            String nickName = userInfo.getNickName();
            hashMap.put(UserConstants.NAME, nickName);
            //如果手机号不为空，openid就返回空
            //前端为：如果openid不为空，绑定手机号，否则不绑定
            if (StringUtils.isEmpty(userInfo.getPhone())){
                hashMap.put(UserConstants.OPENID,userInfo.getOpenid());
            }else {
                hashMap.put(UserConstants.OPENID,"");
            }

            String token = tokenService.getToken(userInfo.getId(), userInfo.getNickName());
            hashMap.put(UserConstants.TOKEN, token);
            //重定向到前端的请求路径吧
            return "redirect:" + UserPropertiesVariable.yytBaseUrl + "/weixin/callback?token=" + token + "&openid=" + openid + "&name=" + nickName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
